package com.fsh.anime.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsh.anime.mapper.PartyInfoMapper;
import com.fsh.anime.mapper.TicketMapper;
import com.fsh.anime.model.dtos.BuyTicketsDto;
import com.fsh.anime.model.pojos.PartyInfo;
import com.fsh.anime.model.pojos.Ticket;
import com.fsh.anime.model.vos.Result;
import com.fsh.anime.model.vos.TicketsVo;
import com.fsh.anime.service.TicketService;
import com.fsh.anime.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket> implements TicketService{
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private PartyInfoMapper partyInfoMapper;

    /**
     * 购买门票
     */
    @Override
    public Result buyTicket(BuyTicketsDto dto) {
        //先判断用户有没有购买过
        Ticket ticket = ticketMapper.selectOne(new QueryWrapper<Ticket>()
                .eq("party_id", dto.getPartyId())
                .eq("user_id", BaseContext.getCurrentId()));
        if (Objects.nonNull(ticket)){
            return Result.error("您已经购买过了，请勿重复购买！");
        }

        //购买门票
        Ticket ticket1=new Ticket(null, dto.getPartyId(), BaseContext.getCurrentId(),dto.getPrice(),null);
        int insert = ticketMapper.insert(ticket1);
        if (insert>0){
            return Result.success("购买成功");
        }
        return null;
    }

    /**
     * 获取当期用户购买的所有门票
     */
    @Override
    public Result getTickets() {
        List<Ticket> tickets = ticketMapper.selectList(new QueryWrapper<Ticket>().eq("user_id", BaseContext.getCurrentId()));
        List<TicketsVo> ticketsVos=new ArrayList<>();
        for (Ticket ticket : tickets) {
            TicketsVo ticketsVo=new TicketsVo();
            ticketsVo.setId(ticket.getId());
            ticketsVo.setCreateTime(ticket.getCreateTime());
            PartyInfo partyInfo = partyInfoMapper.selectById(ticket.getPartyId());
            ticketsVo.setPartyInfo(partyInfo);
            ticketsVos.add(ticketsVo);
        }
        return Result.success(ticketsVos);
    }
}
